# encoding:utf-8
# !/usr/bin/env python
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException 
from tencentcloud.tbp.v20190627 import tbp_client, models 
import os,time,json
from flask import Flask, render_template, request, jsonify, redirect
import utils
import getnews
import numpy as np
import pandas as pd
import datetime

app = Flask(__name__)
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = datetime.timedelta(seconds=2)

# 主页渲染
@app.route('/')
def index_page():
    return render_template('index.html')

# 主页渲染
@app.route('/news/detail',methods = ["GET"])
def news_page():
    index = int(request.args.get("index"))-1
    day = request.args.get("day")

    df = pd.read_csv('news/{}.csv'.format(day),encoding='utf-8-sig')

    context={
        'title':df['title'][index],
        'abstract': df['abstract'][index],
        'content': df['content'][index]
    }

    return render_template('news.html',**context)

@app.route('/news/content',methods = ["POST"])
def getContent():
    index = int(request.args.get("index"))-1
    day = request.args.get("day")
    df = pd.read_csv('news/{}.csv'.format(day),encoding='utf-8-sig')
    return df['content'][index]

def getClient():
    #　绑定secretKey和SecretId
    #cred = credential.Credential("AKIDGJ7YkiBaT6VfZEvvQXO0OXR5VYMufLCo", "XrxoUw97pIWUDhwxiDUXKsCH9l9IDH6h")   
    cred = credential.Credential("AKIDW0NYUAi7aqum8IOSVP8g177tRnvoUwES", "LcopcQ7csuhKm01oxueEgwxkJgqlV4PU")

    httpProfile = HttpProfile()
        #　指定腾讯云接口类型，本项目使用tbp智能对话
    httpProfile.endpoint = "tbp.tencentcloudapi.com"

    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
        # 制定请求服务器归属地
    client = tbp_client.TbpClient(cred, "ap-shanghai", clientProfile) 
    return client

def getNews(day):
    formated_day = utils.getDay(day).strftime('%Y%m%d')

    if not os.path.exists('news/{}.csv'.format(formated_day)):
        getnews.getNews(formated_day)

    df = pd.read_csv('news/{}.csv'.format(formated_day),encoding='utf-8-sig')
    return formated_day,df['title'],df['abstract']


def handleResp(resp):
    if resp.DialogStatus == 'COMPLETE':
        if resp.IntentName == 'ask_news':
            day = resp.SlotInfoList[0].SlotValue
            formated_day,titles,abstracts = getNews(day)
            urls = ['?day=%s&index=%d' % (formated_day,i) for i, x in enumerate(titles, 1)]
            resp.ResultType='6'
            resp.ResponseMessage.GroupList.clear()
            for i, x in enumerate(urls):
                info = models.Group()
                info.ContentType='Text/Plain'
                info.Url=urls[i]
                info.Content=titles[i]
                info.Abstract=abstracts[i]
                resp.ResponseMessage.GroupList.insert(i,info)
        
    elif resp.DialogStatus == 'START':
        print('START')
    elif resp.DialogStatus == 'CONTINUE':
        print('CONTINUE')

    print(resp)
    # 将结果返回前端页面
    return resp.to_json_string()


# /api/chat　接口，只接受POST请求
@app.route('/api/chat',methods = ["POST"])
def _chat():
    # 获取前端发送message消息文本
    text = request.json.get("message")
    context = request.json.get("context")
    
    if context.get('DialogStatus', 'none') == 'ASK':
        print('真正查询结果了')
        if context.get('IntentName', 'none') == 'business_status_query':
            content = '%s的%s当前状态为已完成' % (text,context['SlotInfoList'][0]['SlotValue'])
            result = {"DialogStatus": "COMPLETE", "BotName": "111", "IntentName": "business_status_query", "SlotInfoList": [],
             "InputText": "我在哪里参保", "ResponseMessage": {
             "GroupList": [{"ContentType": "text/plain", "Url": "", "Content": content}]}, 
             "SessionAttributes": "", "ResultType": "1", "RequestId": "41f376ea-16ae-465d-8856-2624a1910198","context":{}}
            return json.dumps(result)
        else:
            result = {"DialogStatus": "COMPLETE", "BotName": "111", "IntentName": "business_status_query", "SlotInfoList": [],
             "InputText": "我在哪里参保", "ResponseMessage": {
             "GroupList": [{"ContentType": "text/plain", "Url": "", "Content": "请重新输入您的问题"}]}, 
             "SessionAttributes": "", "ResultType": "1", "RequestId": "41f376ea-16ae-465d-8856-2624a1910198","context":{}}
            return json.dumps(result)
    else:
        try: 
            client = getClient()

            req = models.TextProcessRequest()
            # 封装请求对象发送参数
            #params = '{"BotId":"3ad196da-1c17-4163-864b-1aab05d8b0a0","BotEnv":"release","TerminalId":"666","InputText":"%s"}' % (text)
            params = '{"BotId":"d1c32794-e70c-45d2-8e65-59f341e12d9e","BotEnv":"dev","TerminalId":"666","InputText":"%s"}' % (text)
            # 发送请求
            req.from_json_string(params)
            # 获取返回腾讯云结构返回结果
            resp = client.TextProcess(req) 

            return handleResp(resp)
        # 如果请求出错，返回错误信息即状态码
        except TencentCloudSDKException as err: 
            error = {"error": err.get_code(),
                    "message": err.get_message(),
                    "requestId": err.get_request_id()}
            return json.dumps(error)

if __name__ == '__main__':
    app.run(host='0.0.0.0',port=5000)